package com.example.demo.utils;
import com.example.demo.store.UserContext;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Log4j2
@Aspect
@Component
public class TokenAspect {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private HttpServletRequest request;
    @Pointcut("within(com.example.demo.controller..*)") // 指定切入点
    public void controllerLayer() {}

    @Before("controllerLayer()")
    public void checkToken() {
        String authorizationHeader = request.getHeader("Authorization");
        String url = request.getRequestURI();
//        不为空，并且 uri不包含 /api/login
        if (authorizationHeader != null && (url != null && !url.contains("/api/user/login"))) {
            String username = jwtUtils.getUsername(authorizationHeader);
            // 你可以在这里将用户名存入线程本地变量，方便后续使用
            UserContext.setCurrentUsername(username);
            log.info("Aspect controller name:" + username);
        }
    }


    @After("controllerLayer()")
    public void clearContext() {
        UserContext.clear();
    }

}

